from typing import List

from nonebot import Bot, logger
from nonebot.adapters import Event
from nonebot.permission import SUPERUSER
from nonebot.plugin import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from openpyxl import Workbook

from ...dao import group_dao, assignment_dao, submit_record_dao
from ...model.assignment import Assignment
from ...model.group import Group
from ...utils.uploader import upload
from ...utils.utils import get_options_list

download_submit_record = on_command("查询作业提交情况", rule=to_me(), permission=SUPERUSER)


@download_submit_record.handle()
async def download_assignment_handler(bot: Bot, event: Event, state: T_State):
    cls_list: List[Group] = await group_dao.getAllClass(bot)
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    state["tag"] = 1
    await download_submit_record.send(cls_options)


@download_submit_record.got("class_no", prompt="你想下载哪个班的作业提交情况呢？")
async def handle_class(bot: Bot, event: Event, state: T_State):
    try:
        num = int(state["class_no"])
    except ValueError:
        await download_submit_record.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await download_submit_record.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))

    assignment_raw = await assignment_dao.getAssignmentOfClass(state["cls_list"][num].gid, state["tag"])
    if len(assignment_raw) == 0:
        await download_submit_record.finish("该班级目前无作业")
    else:
        assignment = list(map(lambda t: Assignment(t), assignment_raw))
        state["assignment_list"] = assignment
        await download_submit_record.send("数据处理中，请稍候")
        class_name = state["cls_list"][num].name
        file_name = f'{class_name}作业提交情况'
        state["submit_file_path"] = await generate_table(file_name, assignment, state["tag"])
        url = await upload(state["submit_file_path"])
        await download_submit_record.finish(f'请到{url} 下载文件')


download_attend_record = on_command("查询签到情况", rule=to_me(), permission=SUPERUSER)

@download_attend_record.handle()
async def download_assignment_handler(bot: Bot, event: Event, state: T_State):
    cls_list: List[Group] = await group_dao.getAllClass(bot)
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    state["tag"] = 2
    await download_submit_record.send(cls_options)


@download_attend_record.got("class_no", prompt="你想下载哪个班的签到情况呢？")
async def handle_class(bot: Bot, event: Event, state: T_State):
    try:
        num = int(state["class_no"])
    except ValueError:
        await download_submit_record.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await download_submit_record.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))

    assignment_raw = await assignment_dao.getAssignmentOfClass(state["cls_list"][num].gid, state["tag"])
    if len(assignment_raw) == 0:
        await download_submit_record.finish("该班级目前无签到")
    else:
        assignment = list(map(lambda t: Assignment(t), assignment_raw))
        state["assignment_list"] = assignment
        await download_submit_record.send("数据处理中，请稍候")
        class_name = state["cls_list"][num].name
        file_name = f'{class_name}签到情况'
        state["submit_file_path"] = await generate_table(file_name, assignment, state["tag"])
        url = await upload(state["submit_file_path"])
        await download_submit_record.finish(f'请到{url} 下载文件')


async def generate_table(file_name, assignment_list: [Assignment], tag):
    wb = Workbook()
    sheet1 = wb.active
    for assignment in assignment_list:
        ws = wb.create_sheet(title=assignment.name)
        record_list = await submit_record_dao.get_submit_record(assignment.id)
        logger.opt(colors=True).info("<g>{}</g>", record_list)
        logger.info("tag is {}", tag)
        if tag == 1:
            ws.append(['学号', '姓名', '是否提交'])
        else:
            ws.append(['学号', '姓名', '是否签到'])
        for record in record_list:
            ws.append([record.studentId, record.studentName, "是" if record.uploaded else "否"])
    wb.remove_sheet(sheet1)
    wb.save(f'static/{file_name}.xlsx')
    logger.info("file_name is {}", file_name)
    return f'static/{file_name}.xlsx'
